package com.example.sentence.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/3/28.
 */
public class MD5Util {

    private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);
    /**
     * Md5加密
     * @param srcs
     * @return
     */
    public static String MD5EncryptByStrs(String... srcs) {
        String md5 = "";
        try {
            StringBuilder str = new StringBuilder();
            for (String src : srcs) {
                str.append(src);
            }
            return DigestUtils.md5DigestAsHex(str.toString().getBytes("UTF-8"));
        } catch (Exception e) {
            logger.error("MD5加密异常", e);
        }
        return md5;
    }

    /**
     * 签名是否一致
     * @param sign
     * @param srcs
     * @return
     */
    public static Boolean equalsIgnoreCase(String sign, String... srcs) {
        Boolean bool = Boolean.FALSE;
        try {
            bool = sign.equalsIgnoreCase(MD5EncryptByStrs(srcs));
        } catch (Exception e) {
            logger.error("校验签名失败",e);
        }
        return bool;
    }

    /**
     * MD5 32位小写加密
     * @param text
     * @return
     */
    public static String encode(String text){
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(text.getBytes());
            StringBuilder sb =new StringBuilder();
            for(byte b:result){
                int number = b&0xff;
                String hex = Integer.toHexString(number);
                if(hex.length() == 1){
                    sb.append("0"+hex);
                }else{
                    sb.append(hex);
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.info("MD5 32位小写加密异常");
            e.printStackTrace();
        }
        return "" ;
    }
}
